package com.medical.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.AuthenticationCashMapper;
import com.medical.entity.AuthenticationCash;
import com.medical.entity.MyException;
import com.medical.entity.ResultBean;
import com.medical.service.AuthenticationCashService;
import com.medical.util.WxPayUtil;

@Service
@Transactional
public class AuthenticationCashServiceImpl implements AuthenticationCashService {
	@Resource
	private AuthenticationCashMapper dao;
	
	@Override
	public ResultBean<Integer> addAuthenticationCash(AuthenticationCash cash) {
		// TODO Auto-generated method stub
		int num=dao.selectCount(new EntityWrapper<AuthenticationCash>().eq("userid", cash.getUserid()).and().eq("states", 1));
		if(num>0) {
			return new ResultBean<>(new MyException("已缴纳保证金"));
		}
		AuthenticationCash ac=dao.getByUserId(cash.getUserid());
		if(ac==null) {
			int count=dao.insert(cash);
			return new ResultBean<>(count);
		}else {
			ac.setMoney(cash.getMoney());
			ac.setStates(cash.getStates());
			ac.setOrdernumber(cash.getOrdernumber());
			ac.setPaytype(cash.getPaytype());
			int count=dao.updateAllColumnById(ac);
			return new ResultBean<>(count);
		}
	}

	@Override
	public ResultBean<Integer> refund(int userid) {
		// TODO Auto-generated method stub
		try {
			AuthenticationCash ac=dao.getByUserId(userid);
			ac.setStates(3);
			
			Boolean pan=WxPayUtil.refund(ac.getOrdernumber(),ac.getMoney().toString(),ac.getMoney().toString());
			if(pan) {
				int count=dao.updateAllColumnById(ac);
				return new ResultBean<Integer>(count);
			}else {
				return new ResultBean<>(new MyException("退款失败"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

}
